import axios from 'axios';
import { getLocalStorage, Message } from '@/utils/utils';
import global from '@/utils/globalUrl';
import { loginLocal } from '@/api/login';
import { getToken } from '@/utils/local';

const pending = [];

const removePending = (config) => {
  for (const key in pending) {
    if (Object.prototype.hasOwnProperty.call(pending, key)) {
      const item = +key;
      const list = pending[key];
      if (list.url === config.url && list.method === config.method && JSON.stringify(list.params) === JSON.stringify(config.params) && JSON.stringify(list.data) === JSON.stringify(config.data)) {
        list.cancel('操作太频繁，请稍后再试');
        pending.splice(item, 1);
      }
    }
  }
};

const instance = axios.create({
  timeout: 8000000
});

instance.interceptors.request.use(
  (config) => {
    removePending(config);
    if (getLocalStorage('token')) {
      config.headers['Token'] = getLocalStorage('token');
    }
    return config;
  },

  (error) => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  async(response) => {
    removePending(response.config);
    const {
      data
    } = response;
    if (!data.success) {
      if (data.message || data.detail) {
        setTimeout(() => {
          const { noWarining } = global;
          const { config: { url, headers }} = response;
          if (!noWarining.includes(url)) {
            if (!headers.notShowMessage) {
              Message(`${data.message && data.message} ${data.detail && data.detail}`);
            }
          }
        }, 300);
      }
    }
    if (process.env.NODE_ENV === 'development') {
      if (response.config.url !== '/mLogin/login' && !getToken()) {
        loginLocal();
      }
    }
    if (response.data.code === 10003) {
      localStorage.clear();
      Message('登录过期'); // 临时
      if (process.env.NODE_ENV === 'development') {
        loginLocal();
      } else {
        setTimeout(() => {
          uni.clearStorageSync();
          window.location.reload();
        }, 1500);
      }
    }
    return response.data;
  },

  (error) => {
    // const confirm = window.confirm('网络连接失败');
    // if(confirm){
    //   localStorage.clear();
    //   window.location.reload();
    // }
    Message('网络错误');
    return Promise.reject(error);
  }
);

export default instance;
